package com.hnevc.musicplayer;

import android.app.Service;
import android.content.Intent;
import android.media.MediaParser;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.Nullable;

import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {

    private MediaPlayer player;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicControl();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //开启创建音乐播放器对象
        player = new MediaPlayer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    //开启计时器用于设置音乐播放器中的播放进度条
    public  void addTimer(){
        Timer timer = new Timer(); //创建计时器对象
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                //重复做的事情
                if (player == null)return;
                    //获取音乐的时长
                    int duration = player.getDuration();
                //获取当前音乐播放进度
                int currentPosition = player.getCurrentPosition();
                Message msg = MainActivity.handler.obtainMessage();
                //将传递的数据进行封装到消息对象中
                Bundle bundle = new Bundle();
                bundle.putInt("duration",duration);
                bundle.putInt("currentPosition",currentPosition);
                msg.setData(bundle);
                // 消息对象数据封装截止  end


                //发送消息
                MainActivity.handler.sendMessage(msg);
            }
        };
        timer.schedule(task,5,500);
    }
    //设置音乐控制器  暂停  播放 继续
    class MusicControl extends Binder{
        //播放
        public void play() {
            try {
                player.reset();//重置当前音乐播放器
                //创建播放器并引入音乐
                player = MediaPlayer.create(getApplicationContext(), R.raw.music);
                player.start();
                addTimer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //暂停
        public void pause(){

        }
        //继续播放
        public void continuePlay(){

        }
        //设置当前的播放进度（进度条拖拽）
        public void seekTo(int progress){
            player.seekTo(progress);
        }
    }

}














